const router = require('koa-router')();
const validator = require('validator');
const {getSHA256} = require('../../module/tools');

router.prefix('/user');

router.get('/', async ctx => {
  ctx.redirect('/admin/user/index')
});

/**
 * 用户列表
 */
router.get('/index', async ctx => {
  const list = await ctx.state.DB.find('user');
  ctx.render('admin/user/index', {
    list
  })
});

/**
 * 增加用户页面
 */
router.get('/add', async ctx => {
  await ctx.render('admin/user/add')
});

/**
 * 执行增加用户
 */
router.post('/doAdd', async ctx => {
  const params = ctx.request.body;
  if (validator.isEmpty(params.fullName) || validator.isEmpty(params.email) || validator.isEmpty(params.password)) {
    ctx.body = {code: -1, msg: '请完善信息'};
  } else if (!validator.isEmail(params.email)) {
    ctx.body = {code: -1, msg: '邮箱格式不正确'};
  } else if (!/^\w{6,20}/.test(params.password)) {
    ctx.body = {code: -1, msg: '密码格式不符合规范'};
  } else if (params.password !== params.retypePassword) {
    ctx.body = {code: -1, msg: '两次输入密码不一致'};
  } else {
    let user = await ctx.state.DB.find('user', {email: params.email});
    if (user && user.length > 0) {
      ctx.body = {code: -1, msg: '此邮箱已被注册'};
    } else {
      try {
        user = {...params, password: getSHA256(params.password)};
        delete user.retypePassword;
        await ctx.state.DB.insert('user', user);
        ctx.redirect('/admin/user/index')
      } catch (e) {
        ctx.body = {code: -1, msg: '增加用户失败'};
      }
    }
  }
});

/**
 * 编辑用户页面
 */
router.get('/edit', async ctx => {
  const user = await ctx.state.DB.find('user', {_id: ctx.state.DB.getObjId(ctx.query.id)});
  await ctx.render('admin/user/edit', user[0]);
});

/**
 * 执行编辑用户
 */
router.post('/doEdit', async ctx => {
  const params = ctx.request.body;
  try {
    await ctx.state.DB.update('user', {_id: ctx.state.DB.getObjId(params._id)}, {
      fullName: params.fullName,
      status: params.status
    });
    ctx.redirect('/admin/user/index')
  } catch (e) {
    ctx.body = {code: -1, msg: '编辑用户失败'};
  }
});

module.exports = router;